"""
UI组件模块 - 定义可重用的UI组件
"""

import os
from PySide2.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QLabel, 
                              QLineEdit, QPushButton, QFileDialog, QProgressBar, 
                              QTextEdit, QFrame, QScrollArea, QGroupBox)
from PySide2.QtCore import Qt, QTimer
from PySide2.QtGui import QFont, QPixmap

from ui_styles import UIStyles
from config import APP_CONFIG


class SidebarComponent(QWidget):
    """侧边栏组件"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.parent_window = parent
        self.ui_styles = UIStyles()
        self.setup_ui()
        
    def setup_ui(self):
        """设置侧边栏UI"""
        self.setFixedWidth(APP_CONFIG['sidebar_width'])
        
        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 30, 0, 30)
        layout.setSpacing(0)
        
        # 应用标题区域
        self.create_title_section(layout)
        
        layout.addSpacing(30)
        
        # 菜单按钮区域
        self.create_menu_section(layout)
        
        # 底部区域
        layout.addStretch()
        self.create_bottom_section(layout)
        
    def create_title_section(self, layout):
        """创建标题区域"""
        title_frame = QFrame()
        title_frame.setStyleSheet(self.ui_styles.get_title_frame_style())
        
        title_layout = QVBoxLayout(title_frame)
        title_layout.setContentsMargins(20, 20, 20, 20)
        title_layout.setSpacing(10)
        
        # 图标和标题的水平布局
        title_h_layout = QHBoxLayout()
        
        # 图标
        logo_label = QLabel()
        try:
            if os.path.exists("icon.ico"):
                logo = QPixmap("icon.ico").scaled(40, 40, Qt.KeepAspectRatio, Qt.SmoothTransformation)
                logo_label.setPixmap(logo)
                logo_label.setFixedSize(40, 40)
            else:
                logo_label.setText("🎬")
                logo_label.setFont(QFont("Segoe UI Emoji", 24))
                logo_label.setAlignment(Qt.AlignCenter)
                logo_label.setFixedSize(40, 40)
        except Exception:
            logo_label.setText("🎬")
            logo_label.setFont(QFont("Segoe UI Emoji", 24))
            logo_label.setAlignment(Qt.AlignCenter)
            logo_label.setFixedSize(40, 40)
        
        # 标题文字
        self.title_label = QLabel(APP_CONFIG['name'])
        self.title_label.setFont(QFont("Microsoft YaHei UI", 14, QFont.Bold))
        self.title_label.setStyleSheet(self.ui_styles.get_title_label_style())
        
        title_h_layout.addWidget(logo_label)
        title_h_layout.addWidget(self.title_label, 1)
        
        # 版本信息
        self.version_label = QLabel(APP_CONFIG['version'])
        self.version_label.setFont(QFont("Microsoft YaHei UI", 9))
        self.version_label.setStyleSheet(self.ui_styles.get_version_label_style())
        self.version_label.setAlignment(Qt.AlignCenter)
        
        title_layout.addLayout(title_h_layout)
        title_layout.addWidget(self.version_label)
        
        layout.addWidget(title_frame)
        
    def create_menu_section(self, layout):
        """创建菜单区域"""
        self.menu_buttons = []
        
        menu_items = [
            ("🎬 抖音视频下载", 0),
            ("⚡ 快手视频下载", 1),
            ("🌸 付费下载区", 2),
            ("⚙️ 设置", 3)
        ]
        
        for text, index in menu_items:
            btn = QPushButton(text)
            btn.setFont(QFont("Microsoft YaHei UI", 10))
            btn.setStyleSheet(self.ui_styles.get_menu_button_style())
            btn.clicked.connect(lambda checked, idx=index: self.switch_page(idx))
            
            self.menu_buttons.append(btn)
            layout.addWidget(btn)
            
        # 设置第一个按钮为激活状态
        if self.menu_buttons:
            self.set_active_button(0)
    
    def create_bottom_section(self, layout):
        """创建底部区域"""
        # 主题切换按钮
        self.theme_toggle_btn = QPushButton("🌙 切换日夜")
        self.theme_toggle_btn.setFont(QFont("Microsoft YaHei UI", 10))
        self.theme_toggle_btn.setStyleSheet(self.ui_styles.get_theme_toggle_style())
        self.theme_toggle_btn.clicked.connect(self.toggle_theme)
        
        layout.addWidget(self.theme_toggle_btn)
        
        # 版权信息
        copyright_label = QLabel("© 2025 代飞工作室")
        copyright_label.setFont(QFont("Microsoft YaHei UI", 8))
        copyright_label.setStyleSheet("color: rgba(255, 255, 255, 0.6); margin: 10px;")
        copyright_label.setAlignment(Qt.AlignCenter)
        
        layout.addWidget(copyright_label)
    
    def switch_page(self, index):
        """切换页面"""
        if self.parent_window:
            self.parent_window.switch_page(index)
        self.set_active_button(index)
    
    def set_active_button(self, index):
        """设置激活按钮"""
        for i, btn in enumerate(self.menu_buttons):
            if i == index:
                btn.setStyleSheet(self.ui_styles.get_active_menu_button_style())
            else:
                btn.setStyleSheet(self.ui_styles.get_menu_button_style())
    
    def toggle_theme(self):
        """切换主题"""
        if self.parent_window:
            self.parent_window.toggle_theme()
    
    def update_theme(self, is_dark_mode):
        """更新主题"""
        self.ui_styles.is_dark_mode = is_dark_mode
        
        # 更新侧边栏背景
        self.setStyleSheet(f"QWidget {{ {self.ui_styles.get_sidebar_style(is_dark_mode)} }}")
        
        # 重新应用标题区域样式（保持固定）
        title_frame = self.findChild(QFrame)
        if title_frame:
            title_frame.setStyleSheet(self.ui_styles.get_title_frame_style())
        
        # 重新应用标题和版本标签样式
        if hasattr(self, 'title_label'):
            self.title_label.setStyleSheet(self.ui_styles.get_title_label_style())
        if hasattr(self, 'version_label'):
            self.version_label.setStyleSheet(self.ui_styles.get_version_label_style())
        
        # 更新主题切换按钮样式
        self.theme_toggle_btn.setStyleSheet(self.ui_styles.get_theme_toggle_style(is_dark_mode))


class DownloadPageComponent(QWidget):
    """下载页面组件基类"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.parent_window = parent
        self.ui_styles = UIStyles()
        
    def create_input_group(self, title, placeholder, browse_button=False):
        """创建输入组"""
        group = QGroupBox(title)
        group.setFont(QFont("Microsoft YaHei UI", 11, QFont.Bold))
        # 设置QGroupBox样式，确保标题文字为白色
        group.setStyleSheet("""
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """)

        layout = QVBoxLayout(group)
        layout.setSpacing(10)
        
        if browse_button:
            input_layout = QHBoxLayout()
            
            input_field = QLineEdit()
            input_field.setPlaceholderText(placeholder)
            input_field.setFont(QFont("Microsoft YaHei UI", 10))
            input_field.setStyleSheet(self.ui_styles.get_input_style(is_dark_mode=True))
            
            browse_btn = QPushButton("浏览")
            browse_btn.setFont(QFont("Microsoft YaHei UI", 9))
            browse_btn.setStyleSheet(self.ui_styles.get_button_style("default"))
            browse_btn.setFixedWidth(80)
            
            input_layout.addWidget(input_field)
            input_layout.addWidget(browse_btn)
            
            layout.addLayout(input_layout)
            
            return group, input_field, browse_btn
        else:
            input_field = QLineEdit()
            input_field.setPlaceholderText(placeholder)
            input_field.setFont(QFont("Microsoft YaHei UI", 10))
            input_field.setStyleSheet(self.ui_styles.get_input_style(is_dark_mode=True))
            
            layout.addWidget(input_field)
            
            return group, input_field
    
    def create_button_group(self, buttons_config):
        """创建按钮组"""
        layout = QHBoxLayout()
        layout.setSpacing(15)
        
        buttons = []
        for text, style_type in buttons_config:
            btn = QPushButton(text)
            btn.setFont(QFont("Microsoft YaHei UI", 10, QFont.Bold))
            btn.setStyleSheet(self.ui_styles.get_button_style(style_type))
            btn.setMinimumHeight(45)
            
            buttons.append(btn)
            layout.addWidget(btn)
        
        return layout, buttons
    
    def create_progress_section(self):
        """创建进度区域"""
        progress_group = QGroupBox("下载进度")
        progress_group.setFont(QFont("Microsoft YaHei UI", 11, QFont.Bold))
        
        layout = QVBoxLayout(progress_group)
        layout.setSpacing(10)
        
        # 进度条
        progress_bar = QProgressBar()
        progress_bar.setStyleSheet("""
            QProgressBar {
                border: 2px solid rgba(255, 255, 255, 0.2);
                border-radius: 8px;
                text-align: center;
                font-weight: bold;
                background: rgba(255, 255, 255, 0.1);
            }
            QProgressBar::chunk {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #667eea, stop:1 #764ba2);
                border-radius: 6px;
            }
        """)
        progress_bar.setMinimumHeight(25)
        
        layout.addWidget(progress_bar)
        
        return progress_group, progress_bar
    
    def create_log_section(self):
        """创建日志区域"""
        log_group = QGroupBox("下载日志")
        log_group.setFont(QFont("Microsoft YaHei UI", 11, QFont.Bold))
        
        layout = QVBoxLayout(log_group)
        layout.setSpacing(10)
        
        # 日志文本框
        log_text = QTextEdit()
        log_text.setFont(QFont("Consolas", 9))
        log_text.setStyleSheet("""
            QTextEdit {
                background: rgba(0, 0, 0, 0.3);
                color: #ffffff;
                border: 2px solid rgba(255, 255, 255, 0.2);
                border-radius: 8px;
                padding: 10px;
            }
        """)
        log_text.setMinimumHeight(200)
        log_text.setReadOnly(True)
        
        # 清空日志按钮
        clear_btn = QPushButton("清空日志")
        clear_btn.setFont(QFont("Microsoft YaHei UI", 9))
        clear_btn.setStyleSheet(self.ui_styles.get_button_style("default"))
        clear_btn.setFixedWidth(100)
        
        button_layout = QHBoxLayout()
        button_layout.addStretch()
        button_layout.addWidget(clear_btn)
        
        layout.addWidget(log_text)
        layout.addLayout(button_layout)
        
        return log_group, log_text, clear_btn
